package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/user/addressBook")
@RestController
@Api(tags = "C端-地址簿接口")
public class AddressBookController {


    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result list(){
        log.info("查询地址");
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        return  Result.success(list);
    }

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result add(@RequestBody AddressBook addressBook){
        log.info("新增地址：{}",addressBook);
        addressBookService.add(addressBook);
        return  Result.success();
    }

    /**
     * 数据回显
     * @param id
     * @return
     */
    @ApiOperation("查询地址byID")
    @GetMapping("/{id}")
    public  Result findByid(@PathVariable Long id) {
        log.info("回显地址ID:{}",id);
        AddressBook addressBook = addressBookService.findByid(id);
        return  Result.success(addressBook);
    }

    /**
     * 修改信息
     * @param addressBook
     * @return
     */
    @ApiOperation("修改信息")
    @PutMapping
    public Result updateMessage(@RequestBody AddressBook addressBook) {
        addressBookService.updateMessage(addressBook);
        return  Result.success();
    }

    /**
     * 查询默认地址
     * @return
     */
    @ApiOperation("默认地址")
    @GetMapping("/default")
    public Result defalut() {
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }
        return Result.error("没有查询到默认地址");
    }
    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    /**
     * 删除地址
     * @param id
     * @return
     */
    @ApiOperation("删除地址")
    @DeleteMapping
    public Result deletes(Long id) {
        log.info("删除地址id：{}",id);
        addressBookService.deletes(id);
        return  Result.success();
    }
}
